<template>
  <div class="container">
    <div class="header">
      <h2>📑 分账协议详情</h2>
      <div class="actions">
        <router-link class="btn secondary" to="/divided/agreements">返回列表</router-link>
      </div>
    </div>

    <div class="card">
      <div class="card-body">
        <div class="info-grid">
          <div><label>协议名称</label><div>{{ agreement?.agreementName || '-' }}</div></div>
          <div><label>协议编号</label><div>{{ agreement?.agreementCode || '-' }}</div></div>
          <div><label>分账周期</label><div>{{ agreement?.dividedCycle ?? '-' }}</div></div>
          <div><label>启用</label><div><span class="badge" :class="enableBadge(agreement?.enableStatus)">{{ enableText(agreement?.enableStatus) }}</span></div></div>
          <div><label>激活</label><div><span class="badge" :class="activationBadge(agreement?.activationStatus)">{{ activationText(agreement?.activationStatus) }}</span></div></div>
          <div><label>开始时间</label><div>{{ formatDate(agreement?.startTime) }}</div></div>
          <div><label>结束时间</label><div>{{ formatDate(agreement?.endTime) }}</div></div>
        </div>
      </div>
    </div>

    <h3>参与者详情</h3>
    <div class="table-container">
      <div class="toolbar">
        <button class="btn primary" @click="openAddDetail">新增参与者</button>
      </div>
      <table class="table">
        <thead>
          <tr>
            <th>参与者</th>
            <th>手机号</th>
            <th>比例</th>
            <th>主账户</th>
            <th>激活</th>
            <th>创建时间</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-if="detailsLoading">
            <td colspan="7" class="loading-state">加载中...</td>
          </tr>
          <tr v-else-if="details.length === 0">
            <td colspan="7" class="empty-state">暂无参与者</td>
          </tr>
          <tr v-else v-for="d in details" :key="d.id" class="table-row">
            <td>{{ d.userName || '-' }}</td>
            <td>{{ d.userPhone || '-' }}</td>
            <td>{{ d.ratio ?? '-' }}</td>
            <td>{{ d.isMasterAccount ? '是' : '否' }}</td>
            <td>
              <span class="badge" :class="activationBadge(d.activationStatus)">{{ activationText(d.activationStatus) }}</span>
            </td>
            <td>{{ formatDate(d.creationTime) }}</td>
            <td>
              <button class="btn small" @click="openEditDetail(d)">编辑</button>
              <button class="btn danger small" @click="onDeleteDetail(d.id)">删除</button>
              <button class="btn secondary small" @click="openConfirmDetail(d.id)">确认</button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 设置收款码 -->
    <div class="card mt-4">
      <div class="card-header"><h3>绑定收款码</h3></div>
      <div class="card-body">
        <div class="form-grid">
          <label>收款码ID列表</label>
          <input class="input" v-model="paymentCodeIdsInput" placeholder="多个以英文逗号分隔" />
          <div></div>
          <button class="btn primary" :disabled="setCodeLoading" @click="onSetPaymentCodes">{{ setCodeLoading ? '提交中...' : '提交' }}</button>
        </div>
      </div>
    </div>

    <!-- 新增/编辑参与者弹窗 -->
    <div v-if="showDetailModal" class="modal-overlay" @click.self="closeDetailModal">
      <div class="modal">
        <div class="modal-header"><h3>{{ editingDetail?.id ? '编辑参与者' : '新增参与者' }}</h3></div>
        <div class="modal-body">
          <div class="form-grid">
            <label>用户ID</label>
            <input class="input" v-model="detailForm.UserId" placeholder="必填" />
            <label>比例（0-1）</label>
            <input class="input" type="number" step="0.01" v-model.number="detailForm.Ratio" placeholder="0.1" />
            <label>主账户</label>
            <select class="input" v-model="detailForm.IsMasterAccount">
              <option :value="false">否</option>
              <option :value="true">是</option>
            </select>
            <label>角色ID</label>
            <input class="input" v-model="detailForm.UserRoleId" placeholder="可选" />
          </div>
          <div v-if="detailError" class="error-message">{{ detailError }}</div>
        </div>
        <div class="modal-footer">
          <button class="btn secondary" @click="closeDetailModal">取消</button>
          <button class="btn primary" :disabled="detailSubmitting" @click="submitDetail">{{ detailSubmitting ? '提交中...' : '提交' }}</button>
        </div>
      </div>
    </div>

    <!-- 确认参与者弹窗（手机号） -->
    <div v-if="showConfirmModal" class="modal-overlay" @click.self="closeConfirmModal">
      <div class="modal">
        <div class="modal-header"><h3>确认参与者</h3></div>
        <div class="modal-body">
          <div class="form-grid">
            <label>手机号</label>
            <input class="input" v-model="confirmPhone" placeholder="必填" />
          </div>
          <div v-if="confirmError" class="error-message">{{ confirmError }}</div>
        </div>
        <div class="modal-footer">
          <button class="btn secondary" @click="closeConfirmModal">取消</button>
          <button class="btn primary" :disabled="confirmSubmitting" @click="submitConfirm">{{ confirmSubmitting ? '提交中...' : '确认' }}</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { isSuccess } from '../services/types'
import { getDividedAgreement, getDividedAgreementDetailList, addDividedAgreementDetail, updateDividedAgreementDetail, deleteDividedAgreementDetail, confirmDividedAgreementDetail, setDividedAgreementPaymentCodes, type DividedAgreementResponse, type DividedAgreementDetailResponse, type DividedAgreementDetailRequest, type SetDividedAgreementPaymentCodesRequest } from '../services/divided'

const route = useRoute()
const id = String(route.params.id || '')
const loading = ref(false)
const agreement = ref<DividedAgreementResponse | null>(null)
const detailsLoading = ref(false)
const details = ref<DividedAgreementDetailResponse[]>([])

// 设置收款码
const paymentCodeIdsInput = ref('')
const setCodeLoading = ref(false)

// 参与者弹窗
const showDetailModal = ref(false)
const editingDetail = ref<DividedAgreementDetailResponse | null>(null)
const detailSubmitting = ref(false)
const detailError = ref('')
const detailForm = reactive<DividedAgreementDetailRequest>({ DividedAgreementId: id, UserId: '', Ratio: 0.1, IsMasterAccount: false, UserRoleId: '' })

// 确认参与者弹窗
const showConfirmModal = ref(false)
const confirmDetailId = ref('')
const confirmPhone = ref('')
const confirmSubmitting = ref(false)
const confirmError = ref('')

/**
 * 文件级注释：
 * 分账协议详情页面，展示协议基础信息、参与者列表，并提供新增/编辑/删除/确认参与者以及协议绑定收款码的功能。
 * 所有接口以 code === 0 判定为成功。
 */

/**
 * 函数级注释：加载协议详情
 * @returns void
 * @throws 可能抛出网络异常
 */
async function loadAgreement() {
  if (!id) return
  loading.value = true
  try {
    const res = await getDividedAgreement(id)
    if (isSuccess(res)) {
      agreement.value = res.data || null
    } else {
      console.warn('获取协议详情失败:', res?.message)
      agreement.value = null
    }
  } catch (e) {
    console.error('接口异常:', e)
  } finally {
    loading.value = false
  }
}

/**
 * 函数级注释：加载参与者列表
 * @returns void
 */
async function loadDetails() {
  detailsLoading.value = true
  try {
    const res = await getDividedAgreementDetailList(id)
    if (isSuccess(res)) {
      details.value = res.data || []
    } else {
      details.value = []
      console.warn('获取参与者失败:', res?.message)
    }
  } catch (e) {
    console.error('接口异常:', e)
  } finally {
    detailsLoading.value = false
  }
}

/**
 * 函数级注释：打开新增参与者弹窗
 * @returns void
 */
function openAddDetail() {
  editingDetail.value = null
  detailForm.DividedAgreementId = id
  detailForm.UserId = ''
  detailForm.Ratio = 0.1
  detailForm.IsMasterAccount = false
  detailForm.UserRoleId = ''
  detailError.value = ''
  showDetailModal.value = true
}

/**
 * 函数级注释：打开编辑参与者弹窗
 * @param d 参与者详情
 * @returns void
 */
function openEditDetail(d: DividedAgreementDetailResponse) {
  editingDetail.value = d
  detailForm.Id = d.id
  detailForm.DividedAgreementId = d.dividedAgreementId
  detailForm.UserId = d.userId
  detailForm.Ratio = d.ratio
  detailForm.IsMasterAccount = !!d.isMasterAccount
  detailForm.UserRoleId = d.userRoleId
  detailError.value = ''
  showDetailModal.value = true
}

/**
 * 函数级注释：关闭参与者弹窗
 * @returns void
 */
function closeDetailModal() { showDetailModal.value = false }

/**
 * 函数级注释：提交新增/编辑参与者
 * @returns void
 * @throws 可能抛出网络异常
 */
async function submitDetail() {
  if (!detailForm.UserId || !detailForm.DividedAgreementId) {
    detailError.value = '用户ID与协议ID为必填项'
    return
  }
  detailSubmitting.value = true
  detailError.value = ''
  try {
    const api = detailForm.Id ? updateDividedAgreementDetail : addDividedAgreementDetail
    const res = await api(detailForm)
    if (isSuccess(res)) {
      showDetailModal.value = false
      await loadDetails()
    } else {
      detailError.value = res?.message || '提交失败'
    }
  } catch (e: any) {
    detailError.value = e?.message || '网络异常'
  } finally {
    detailSubmitting.value = false
  }
}

/**
 * 函数级注释：删除参与者
 * @param id 详情ID
 * @returns void
 */
async function onDeleteDetail(id?: string) {
  if (!id) return
  try {
    const res = await deleteDividedAgreementDetail({ Ids: [id] })
    if (isSuccess(res)) {
      await loadDetails()
    } else {
      console.warn('删除失败:', res?.message)
    }
  } catch (e) {
    console.error('删除异常:', e)
  }
}

/**
 * 函数级注释：打开确认参与者弹窗
 * @param id 详情ID
 * @returns void
 */
function openConfirmDetail(id?: string) {
  confirmDetailId.value = id || ''
  confirmPhone.value = ''
  confirmError.value = ''
  showConfirmModal.value = true
}

/**
 * 函数级注释：关闭确认弹窗
 * @returns void
 */
function closeConfirmModal() { showConfirmModal.value = false }

/**
 * 函数级注释：提交确认参与者（手机号）
 * @returns void
 */
async function submitConfirm() {
  if (!confirmDetailId.value || !confirmPhone.value) {
    confirmError.value = '详情ID与手机号为必填项'
    return
  }
  confirmSubmitting.value = true
  confirmError.value = ''
  try {
    const res = await confirmDividedAgreementDetail(confirmDetailId.value, confirmPhone.value)
    if (isSuccess(res)) {
      showConfirmModal.value = false
      await loadDetails()
    } else {
      confirmError.value = res?.message || '确认失败'
    }
  } catch (e: any) {
    confirmError.value = e?.message || '网络异常'
  } finally {
    confirmSubmitting.value = false
  }
}

/**
 * 函数级注释：绑定收款码
 * @returns void
 */
async function onSetPaymentCodes() {
  if (!id) return
  const ids = paymentCodeIdsInput.value.split(',').map(s => s.trim()).filter(Boolean)
  const payload: SetDividedAgreementPaymentCodesRequest = { DividedAgreementId: id, PaymentCodeIds: ids }
  setCodeLoading.value = true
  try {
    const res = await setDividedAgreementPaymentCodes(payload)
    if (isSuccess(res)) {
      paymentCodeIdsInput.value = ''
    } else {
      console.warn('设置收款码失败:', res?.message)
    }
  } catch (e) {
    console.error('接口异常:', e)
  } finally {
    setCodeLoading.value = false
  }
}

/**
 * 函数级注释：格式化时间
 * @param v 时间字符串
 * @returns 中文本地时间或 '-'
 */
function formatDate(v?: string) {
  if (!v) return '-'
  try { return new Date(v).toLocaleString('zh-CN') } catch { return v }
}
function enableText(s?: number) { if (s === 1) return '启用'; if (s === 0) return '禁用'; return '未知' }
function enableBadge(s?: number) { if (s === 1) return 'badge active'; if (s === 0) return 'badge inactive'; return 'badge' }
function activationText(s?: number) { if (s === 1) return '已激活'; if (s === 0) return '未激活'; return '未知' }
function activationBadge(s?: number) { if (s === 1) return 'badge active'; if (s === 0) return 'badge inactive'; return 'badge' }

onMounted(async () => { await loadAgreement(); await loadDetails() })
</script>

<style scoped>
.header { display: flex; align-items: center; justify-content: space-between; }
.card { border: 1px solid var(--border); border-radius: var(--radius-lg); background: var(--card-bg); box-shadow: var(--shadow-sm); margin-bottom: var(--space-4); }
.card-header { padding: var(--space-4); border-bottom: 1px solid var(--border); }
.card-body { padding: var(--space-4); }
.info-grid { display:grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: var(--space-3); }
label { color: var(--text-secondary); font-size: var(--text-sm); }
.table { width: 100%; border-collapse: collapse; }
.table th, .table td { padding: 12px; border-bottom: 1px solid var(--border); }
.badge { padding: 2px 8px; border-radius: var(--radius); font-size: var(--text-sm); }
.badge.active { background: var(--primary-50); color: var(--primary-700); }
.badge.inactive { background: var(--bg-secondary); color: var(--text-secondary); }
.table-row:hover { background: var(--bg-secondary); }
.loading-state, .empty-state { text-align: center; padding: var(--space-6); color: var(--text-secondary); }
.toolbar { padding: var(--space-2) 0; }
.form-grid { display:grid; grid-template-columns: 120px 1fr; gap: var(--space-3); align-items: center; }
.error-message { color: var(--danger); padding: var(--space-2) 0; }
.mt-4 { margin-top: var(--space-4); }

.modal-overlay { position: fixed; inset: 0; background: rgba(0,0,0,0.3); display:flex; align-items: center; justify-content: center; }
.modal { width: 600px; max-width: 90vw; background: var(--card-bg); border: 1px solid var(--border); border-radius: var(--radius-lg); box-shadow: var(--shadow-lg); }
.modal-header { padding: var(--space-4); border-bottom: 1px solid var(--border); }
.modal-body { padding: var(--space-4); }
.modal-footer { padding: var(--space-4); display:flex; justify-content: flex-end; gap: var(--space-2); border-top: 1px solid var(--border); }

@media (max-width: 768px) {
  .form-grid { grid-template-columns: 1fr; }
}
</style>

